package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.mapper.log.PushHeadLogMapper;
import com.tulele.vtool.bus.model.ArticleInfo;
import com.tulele.vtool.bus.model.UserBrandInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.*;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserGroupOpenId;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.util.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
@Slf4j
public class NewUserMsgAsyncTask {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IArticleService iArticleService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserBrandService userBrandService;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Autowired
    private PushHeadLogMapper pushHeadLogMapper;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private UserGroupGzhService userGroupGzhService;


    //新年
    @Async("taskExecutor")
    public void execute20210208(String redisKey, Integer headId, UserInfo userInfo, String profile) throws Exception {

        Integer ret = 2;

        WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
        wxPushUserInfo.setOpenId(userInfo.getOpenId());

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            wxPushUserInfo.setOpenId(ugoId.getOpenId());
        }

        wxPushUserInfo.setUserId(userInfo.getUserId());

        if (wxPushUserInfo != null) {
            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
            WxMpKefuMessage.WxArticle wxArticle = null;
            String kefuMsg = "";

            //20200530 循环推送
            Integer number = 1;
            Object pushNumberObj = redisCacheUtil.getCacheObject("push930Number" + wxPushUserInfo.getUserId());
            if (pushNumberObj != null) {
                number = (Integer) pushNumberObj;
                if (number > 2) {
                    number = 1;
                }
            }
            redisCacheUtil.setCacheObject("push930Number" + wxPushUserInfo.getUserId(), number + 1, 100000);

            if (number.equals(1)) {

                kefuMsg = "\uD83C\uDF39，恭喜！恭喜！\n\n" +
                        "\uD83D\uDE0D <a href=\""+sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1"+"\">您抽到一张优惠抵用券</a>\n\n"+
                        "\uD83D\uDC49 <a href=\""+sysGzh.getOpenMemberMenuUrl() + "\">点击领取优惠券 \uD83D\uDC48</a>";

            } else if (number.equals(2)) {
                if (userInfo.getVipStatus() == null || userInfo.getVipStatus().equals(0)) {// 只发非会员
                    String articleTypeName = "";// 默认值
                    String articleTypeIds = iArticleService.getUserArticleType(userInfo.getUserId());// 获取用户关注的类型
                    if (StringUtils.isNotBlank(articleTypeIds)) {
                        String userFirstArticleType = articleTypeIds.split(",")[0];
                        articleTypeName = iArticleService.getArticleTypeNameById(Integer.valueOf(userFirstArticleType));// 第一个类型的名称
                    }

                    wxArticle = new WxMpKefuMessage.WxArticle();
                    wxArticle.setTitle("【" + articleTypeName + "】今日限量优惠券！");//平时
                    wxArticle.setDescription("每天限名额领取，先抢了再说！");
                    wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg"+"?"+SysConstant.OSS_PAR_80_80);

                    String accessUrl = sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";

                    wxArticle.setUrl(accessUrl);
                } else {
                    return;// 会员就不推送消息了
                }

            }

            WxMpKefuMessage message = null;
            if (!kefuMsg.equals("")) {
                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }
                message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
            } else {
                message = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(wxPushUserInfo.getOpenId()).build();
            }

            String detailLog = "";
            try {

                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                if(weixinService==null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile,weixinService);
                }

                Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                if (sendRet) {
                    ret = 0;
                    detailLog = "成功";
                } else {
                    ret = 1;
                    detailLog = "失败";
                }
            } catch (WxErrorException e) {
                ret = 2;
                detailLog = e.getMessage();
            }
            PushDetailLog pushDetailLog = new PushDetailLog();
            pushDetailLog.setGzhCode(profile);
            pushDetailLog.setUserId(wxPushUserInfo.getUserId());
            pushDetailLog.setMsgType(7);  //9:30 优惠推送
            pushDetailLog.setPushTime(new Date());
            pushDetailLog.setHeadId(headId);
            pushDetailLog.setResult(ret);
            pushDetailLog.setMsg(detailLog);
            pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        }
    }

    //年末修改前
    @Async("taskExecutor")
    public void execute20211130(String redisKey, Integer headId, UserInfo userInfo, String profile) throws Exception {

        Integer ret = 2;

        WxPushUserInfo wxPushUserInfo  = new WxPushUserInfo();
        wxPushUserInfo.setOpenId(userInfo.getOpenId());

        UserGroupOpenId ugoId = userGroupGzhService.getUserOpenId(profile, userInfo.getUserId());
        if (ugoId != null) {
            wxPushUserInfo.setOpenId(ugoId.getOpenId());
        }

        wxPushUserInfo.setUserId(userInfo.getUserId());

        if (wxPushUserInfo != null) {
            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
            WxMpKefuMessage.WxArticle wxArticle = null;
            String kefuMsg = "";

            //20200530 循环推送
            Integer number = 1;
            Object pushNumberObj = redisCacheUtil.getCacheObject("push930Number" + wxPushUserInfo.getUserId());
            if (pushNumberObj != null) {
                number = (Integer) pushNumberObj;
                if (number > 2) {
                    number = 1;
                }
            }
            redisCacheUtil.setCacheObject("push930Number" + wxPushUserInfo.getUserId(), number + 1, 100000);

            if (number.equals(1)) {

                kefuMsg =
                        "\uD83D\uDD14 限时优惠 ㊙ 今天优惠看过来>\n\n" +
                                "\uD83D\uDE0D 开通年卡多送时间，价格不变！\n\n" +
                                "\uD83D\uDC96 <a href=\""+sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1"+"\">赶快激活VIP，开启获客机会！</a>\n\n" +
                                "\uD83D\uDC49 <a href=\""+sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1"+"\">点我领取优惠升级>>></a>";

            } else if (number.equals(2)) {
                wxArticle = new WxMpKefuMessage.WxArticle();
                wxArticle.setTitle("【限时优惠】送您30元会员立减券");//平时
                wxArticle.setDescription("最高立减30元，点击领取>");
                wxArticle.setPicUrl("https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/wxTouXiang/couponLogo.jpg"+"?"+SysConstant.OSS_PAR_80_80);

                String accessUrl = sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1";

                wxArticle.setUrl(accessUrl);
            }

            WxMpKefuMessage message = null;
            if (!kefuMsg.equals("")) {
                if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                    kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                }
                message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
            } else {
                message = WxMpKefuMessage.NEWS().addArticle(wxArticle).toUser(wxPushUserInfo.getOpenId()).build();
            }

            String detailLog = "";
            try {

                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                if(weixinService==null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile,weixinService);
                }

                Boolean sendRet = weixinService.getKefuService().sendKefuMessage(message);
                if (sendRet) {
                    ret = 0;
                    detailLog = "成功";
                } else {
                    ret = 1;
                    detailLog = "失败";
                }
            } catch (WxErrorException e) {
                ret = 2;
                detailLog = e.getMessage();
            }
            PushDetailLog pushDetailLog = new PushDetailLog();
            pushDetailLog.setGzhCode(profile);
            pushDetailLog.setUserId(wxPushUserInfo.getUserId());
            pushDetailLog.setMsgType(7);  //9:30 优惠推送
            pushDetailLog.setPushTime(new Date());
            pushDetailLog.setHeadId(headId);
            pushDetailLog.setResult(ret);
            pushDetailLog.setMsg(detailLog);
            pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        }
    }

}
